<template>

	<view class="root" v-if="loaded">
		<view class="blog-container" :key="blog.id">
			<image :src="blog.user.avatar" mode="aspectFill" class="img-head"></image>
			<text class="blog-title">{{blog.title}}</text>
			<text class="blog-author">{{blog.user.nickName}}@{{blog.createTime}}</text>
			<rich-text :nodes="blog.content" class="item-content"></rich-text>
			<text class="iconfont icon-shoucang img-oper"></text>
			<view>
				<text v-for="(tag,idx) in blog.tags" class="item-tag">{{tag}}</text>
			</view>

			<!-- <image :src="blog.user.avatar" mode="aspectFill" class=img-head></image>
	 -->
			<image :src="blog.avatarurl" mode="aspectFill" class="img-head"></image>
			<view :src="blog.avatarurl" mode="aspectFill" class="img-head">
				<!-- <image @click="changGood(blog.id,true)" src="../../static/icons/ic_good.png" class="icon"></image> -->
				<!-- <image @click="changGood(blog.id,false)" src="../../static/icons/ic_good_fill.png" class="icon"></image> -->
				<image @click.stop="onChangeGood(blog.id,true)" v-if="!hasGood" src="../../static/icons/ic_good.png"
					class="icon"></image>

				<image @click.stop="onChangeGood(blog.id,false)" v-else src="../../static/icons/ic_good_fill.png"
					class="icon"></image>
				<text class="icon-text">{{blog.good}}</text>
				<image src="../../static/icons/ic_comment.png" class="icon"></image>
				<!-- <text class="icon-text">{{blog.comments.length}}</text> -->
				<text class="icon-text">{{blog.length}}</text>
				<image src="../../static/icons/ic_count.png" class="icon"></image>
				<text class="icon-text">{{blog.readCount}}</text>
			</view>
			<text @click.stop="onChangeGood(blog,false)" v-if="!hasGood" class="iconfont icon-dianzan icon"></text>
			<text @click.stop="onChangeGood(blog,true)" v-else class="iconfont icon-dianzan1 icon"></text>
			<text class="icon-text">{{blog.good}}</text>
			<text class="iconfont icon-pinglun icon"></text>
			<text class="icon-text">{{blog.comments.length}}</text>
			<text class="iconfont icon-icon- icon"></text>
			<text class="icon-text">{{blog.readCount}}</text>

		</view>
		<view v-if="hasComment" class="blog-margin-container">
			<view v-for="(item,index) in parents" :key="item.id">
				<view class="parent-container">
					<text class="cmt-author">{{item.nickName}}</text>
					<view class="cmt-time-container">
						<text class="cmt-time">{{item.createTime}}</text>
						<text v-if="canDelete(item)" class="txt-delete"
							@click.stop="deleteCmt(item,true,index)">[删除]</text>
					</view>
					<image :src="item.avatar" mode="aspectFill" class="cmt-avatar"></image>
					<text class="cmt-content" @click="clickToReply(item)">{{item.content}}</text>
				</view>
				<view v-if="replies[index].length>0" class="replies-container"></view>
				<view v-for="(reply,idx) in replies[index]" :key="reply.id" class="reply-item">
					<view class="reply-info">
						<text class="reply-author">{{reply.nickName}}:</text>
						<text class="reply-to">@{{reply.toUser}}</text>
						<text class="reply-time">{{reply.createTime}}</text>
						<text v-if="canDelete(reply)" class="txt-delete"
							@click.stop="deleteCmt(reply,false,index)">[删除]</text>
					</view>
					<text class="reply-content" @click="clickToReply(reply)">{{reply.content}}</text>
				</view>
				<view v-if="index < parents.length - 1" class="cmt-line"></view>
			</view>

		</view>
		<view class="input-container">
			<image :src="userAvatar" mode="aspectFill" class="input-avatar" @click.stop="onLogin()"></image>
			<textarea auto-height v-model="inputValue" :placeholder="inputHolder" class="input-area"
				placeholder-class="input-holder" @input="inputGetValue" />
			<image src="../../static/icons/commit.png" class="input-commit" @click="pushCmtValue"></image>
		</view>
		<login-dialog ref="shell" @afterLogin="afterLogin"></login-dialog>

		</login-dialog>

	</view>
	</view>
</template>

<script>
	import {
		stdout
	} from 'process';
	let cmtValue = "";
	let parentId = null;
	let app = getApp()
	export default {
		data() {
			return {
				id: "",
				blog: [],
				good_ids: [],
				hasGood: false,
				loaded: false,
				parents: [],
				replies: [],
				hasComment: false,
				inputValue: "",
				inputHolder: "请输入内容",
				userAvatar: "../../static/icons/default_user.png"
			}
		},
		onLoad(options) {
			let id = options.id
			let good_ids = uni.getStorageSync(this.$params.key_good_ids)
			if (good_ids) {
				this.hasGood = good_ids.indexOf(id) >= 0
			}
			this.addReadCount(id);
			this.$noti.add(this.$params.noti_login_status, this.afterLogin, this)
		},
		onUnload() {
			this.$noti.remove(this.$params.noti_login_status, this)
		},

		mounted() {
			if (!app.globalData.token == 0) {
				this.userAvatar = this.$params.host + getApp().globalData.avatar;
			}
		},
		methods: {
			deleteCmt(cmt, isParent, index) {
				let url = this.$params.host + this.$params.action_blogs_del_comment + cmt.id
				let data = {
					token: app.globalData.token
				}
				uni.showModal({
					title: '删除评论',
					content: '确定删除该评论吗\n注意。子评论也会同时删除',
					showCancel: true,
					cancelText: '算了',
					confirmText: '删除',
					success: res => {
						if (res.confirm) {
							uni.showLoading({
								title: '删除评论......',
								mask: false
							});
							this.$request.deleteParams(url, data, res => {
								uni.showToast({
									title: res.message,
									icon: "none"
								});
								if (res.success) {
									if (isParent) {
										let list = this.replies[index]
										list.push(this.parents[index])
										this.$util.remove(this.parents, index)
										this.$util.remove(this.replies, index)
										this.blog.comments = this.blog.comments.filter(c => list.every(
											r => r.id != c.id))
									} else {
										let children = this.getChildren(cmt, this.replies[index])
										children.push(cmt)
										this.replies[index] = this.replies[index].filter(r => children
											.every(c => c.id != r.id))
										this.blog.comments = this.blog.comments.filter(c => children
											.every(r => r.id != c.id))
									}
								}
							}, () => {
								uni.hideLoading()
							})
						}
					},
					fail: () => {},
					complete: () => {}
				});
			},
			onLogin() {
				this.$refs.shell.show();
			},
			let url = this.$params.host + (!isGood ? this.$params.action_good : this.$params.action_del_good);
			let data = {
				"id": blog.id,
			}
			this.$request.postParam(url, data, res => {
				this.blog.good = res.data;
				let blog_data = {
										"picture": blog.picture,
										"id": blog.id,
										"title": blog.title
									}
				if (isGood) {
					this.hasGood = !this.hasGood;
					this.good_ids.splice(this.good_ids.indexOf(blog_data), 1);
				} else {
					this.hasGood = !this.hasGood;
					this.good_ids.push(blog_data);
				}
				let pages = getCurrentPages();
				let pre = pages[pages.length - 2];
				// pre.refreshGood(this.good_ids);
				uni.setStorageSync(this.$params.key_good_ids, this.good_ids);

			}, () => {

			});
		},
		addReadCount(id) {
			let url = this.$params.host + this.$params.action_read_count
			let data = {
				"id": id
			}
			this.$request.postParam(url, data, res => {
				let count = res.data
				this.$noti.post(this.$params.noti_refresh_count, {
					id,
					count
				})
			}, () => {

				this.getBlog(id)
			})
		},
		refreshPreviousPage(id){
						//
						let pages = getCurrentPages();
						let pre = pages[pages.length-2];
						pre.refreshCount(id,this.blog.readCount);
						},

		getBlog(id) {
			let url = this.$params.host + this.$params.action_blog + id
			console.log(url);
			this.$request.get(url, res => {
				this.loaded = true
				let blog = res.data
				uni.setNavigationBarTitle({
					title: blog.user.nickName,
				})
				if (!blog.picture.startsWith("http")) {
					blog.picture = this.$params.host + blog.picture
				}
				blog.user.avatar = this.$params.host + blog.user.avatar
				blog.content = blog.content.replace(/\<img/gi, '<img class="img" ')
				blog.createTime = this.$util.formatTime(new Date(blog.createTime))
				this.blog = blog
				this.hasComment = true;
				this.formatComments(this.blog.comments)
			}, () => {

			});

		},
		formatComments(comments) {
			if (comments.length == 0) {
				return
			}
			let rootComments = []
			comments.forEach(c => {
				if (!c.avatar.startsWith("/http")) {
					c.avatar = this.$params.host + c.avatar.substring(1)
				} else {
					c.avatar = this.$params.host + c.avatar.substring(1)
				}
				c.createTime = this.$util.formatTime(new Date(c.createTime))
				if (c.parentId == null) {
					rootComments.push(c)
				}
			})
			rootComments.sort((c1, c2) => {
				return new Date(c2.createTime).getTime() - new Date(c1.createTime).getTime()
			})
			let replies = new Array(rootComments.length).fill([])
			let index = 0
			rootComments.forEach(r => {
				let cmmts = []
				cmmts = cmmts.concat(this.getChildren(r, comments))
				replies[index++] = cmmts
				comments = comments.filter(c => cmmts.every(cc => cc.id != c.id))
			})
			this.parents = rootComments
			this.replies = replies
		},
		getChildren(parent, comments) {
			//todo:得到parent所有的子评论
			let childrenComments = [];
			comments.forEach(comment => {
				if (parent.id == comment.parentId) {
					comment.toUser = parent.nickName;
					childrenComments.push(comment);
					let cmmts = comments.filter(cmt => cmt.id != comment.id)
					childrenComments.concat(this.getChildren(comment, cmmts));
				}
			})
			return childrenComments;
		},
		canDelete(item) {
			return app.globalData.ytpe == 1 || item.avatar == this.userAvatar
		},
		clickToReply(item) {
			parent_Id = item.id
			this.inputHolder = "@" + item.nickName
		},
		inputGetValue(e) {
			cmtValue = e.detail.value
		},
		pushCmtValue() {
if (app.globalData.token.length == 0) {
					this.$refs.shell.show();
					return;
				}
			if (cmtValue.length == 0) {
				uni.showToast({
					title: "还没输入哦",
					icon: 'none',
				});
			}
			let data = {
				nick_name: app.globalData.nickName,
				avatar: "/" + app.globalData.avatar,
				email: app.globalData.email,
				content: cmtValue,
				blog_id: this.blog.id,
				parentId: parentId,
				token: app.globalData.token,
				is_owner: app.globalData.uid == this.blog.user.id,
			}


			this.$request.post(this.$params.host + this.$params.action_blogs_add_comment, data, res => {
				if (!res.success) {
					uni.showToast({
						title: res.message,
						icon: "none"
					})

					return;
				}
				console.log(res);
				let cmt = {};
				cmt.avatar = res.data.avatar;
				cmt.blogId = res.data.blogId;
				cmt.content = res.data.content;
				cmt.createTime = res.data.createTime;
				cmt.email = res.data.email;
				cmt.id = res.data.id;
				cmt.nickName = res.data.nickName;
				cmt.owner = res.data.owner;
				cmt.parentId = res.data.parentId;
				let comments = this.blog.comments.concat(cmt);
				this.blog.comments = comments;

				this.hasComment = this.blog.comments.length > 0;
				this.inputHolder = "请输入评论......";
				this.inputValue = "";
				cmtValue = "";
				parentId = null;
				//刷新列表页的评论数
				this.cmtCount = this.blog.comments.length;
				this.$noti.post(this.$params.noti_refresh_comment_count, {
					id: this.blog.id,
					comments: comments,
				})

			}, () => {})

		},


		afterLogin() {
			this.userAvatar = this.$params.host + getApp().globalData.avatar;
		}
	}
	}
</script>

<style>
	@import url("../index/index.css");
	@import url("../../common/iconfont.css");
</style>
